<template>
  <div class="image-uploader">
    <input type="file" multiple hidden ref="fileInput" @change="handleFiles" />
    <button @click="triggerUpload">上传图片</button>

    <div class="preview-grid">
      <div v-for="(file, index) in previews" :key="index" class="preview-item">
        <img :src="file.preview" />
        <button class="remove-btn" @click="removeFile(index)">×</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      previews: []
    }
  },
  methods: {
    triggerUpload() {
      this.$refs.fileInput.click()
    },
    handleFiles(e) {
      const files = Array.from(e.target.files)
      files.forEach((file) => {
        this.previews.push({
          file,
          preview: URL.createObjectURL(file)
        })
      })
    },
    removeFile(index) {
      this.previews.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 10px;
  margin-top: 10px;
}

.preview-item {
  position: relative;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.preview-item img {
  width: 100%;
  height: 100px;
  object-fit: cover;
}

.remove-btn {
  position: absolute;
  top: 2px;
  right: 2px;
  padding: 2px 6px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 50%;
}
</style>
